<template>
  <div style="background-color: #F5F5F5; height: 870px" class="awsCenter">
    <div style="background-color: white; width: 70%; height: 95%; border-radius: 25px; padding: 20px;">
      <h2 style="margin-bottom: 30px">我的咨询记录</h2>
      <el-table :data="appointments" style="width: 100%" height="600px" :row-style="{ height: '80px' }">
        <el-table-column prop="name" label="咨询师" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="weekend" label="预约星期" />
        <el-table-column prop="times" label="咨询时间段" />
        <el-table-column prop="room" label="地点" />
        <el-table-column prop="status" label="预约状态">
          <template v-slot="{ row }">
            <el-tag :type="formatStatus(row)">{{row.status}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdat" label="预约时间" width="200"/>

        <el-table-column label="说明信息">
          <template v-slot="{ row }">
            <text v-if="row.status=='已预约'">请准时前往</text>
            <el-button
                v-else
                link
                type="primary"
                @click="row.status=='已取消'?showCancelDialog(row):complete(row)"
            >
              {{row.status=='已取消'?"点击查看":row.isFeed?"点击查看":"点击查看"}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="awsCenter" style="margin-top: 20px">
        <el-pagination
            v-model:current-page="currentPage1"
            :page-size="10"
            :size="size"
            :disabled="disabled"
            :background="background"
            layout="total, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>


      <el-dialog :title="`取消预约 - ${selectedAppointment?.name}`" v-model="cancelDialogVisible" width="500">
        <el-input
            type="textarea"
            disabled
            placeholder="请输入取消原因"
            v-model="remark"
            rows="4"
        />

      </el-dialog>


      <el-dialog
          v-model="showComplete"
          title="来访者评估"
          width="500"
          align-center
      >
        <el-form :data="assessForm" label-position="top">
          <el-form-item label="问题点">
            <el-input disabled :rows="4" v-model="assessForm.problem" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="解决方案">
            <el-input disabled :rows="4" v-model="assessForm.plan" type="textarea"></el-input>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button color="#8adba0" type="primary" v-if="flag" @click="feedback">
              <text style="color:white;">查看反馈</text>
            </el-button>
            <el-button color="#8adba0" v-else type="primary" @click="feedback">
              <text style="color:white;">填写反馈</text>
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ComponentSize } from 'element-plus'


const currentPage1 = ref(1)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const total=ref(0)
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = async (val: number) => {
  const body={
    current:val,
    pageSize:10,
    userid:parseInt(userStore.user.userid)
  }
  let res=await getCouByUserIdService(body)
  if (res.code===200){
    console.log(res.data)
    appointmentsFormat(res.data.data)
    total.value=res.data.total
  }
}
import {onMounted, ref } from 'vue';
import {
  cancelService,
  completeService,
  getAssessIdService,
  getByUserIdService,
  getCouByUserIdService
} from "@/api/appointment.js";
import {useUserStore} from "@/stores/user/user";
import {ElMessage} from "element-plus";
import router from "@/router";
import {isFeedService} from "@/api/feedback";
const userStore=useUserStore()

const assessForm=ref({
  problem:'',
  plan:''
})
const formatStatus=((row)=>{
  if (row.status==='已预约'){
    return 'primary'
  }else if(row.status==='已完成'){
    return 'success'
  }else if (row.status==='已取消'){
    return 'error'
  }
})

onMounted(async ()=>{
  await getList()
})
const getList=(async ()=>{
  const body={
    current:currentPage1.value,
    pageSize:10,
    userid:parseInt(userStore.user.userid)
  }
  let res=await getCouByUserIdService(body)
  if (res.code===200){
    console.log(res.data)
    appointmentsFormat(res.data.data)
    total.value=res.data.total
  }
})

const appointmentsFormat=((data)=>{
  data.forEach(item=>{
    //转换星期
    item.weekend=convertToWeekday(item.weekend)

    //转换时间段
    item.times=formatTimeRange(item.startTime,item.endTime)

    //转换状态
    item.status=convertStatus(item.status)

    let str=item.createdat.toString().split('T')
    item.createdat=str[0]+" "+str[1].split(".")[0]

  })
  appointments.value=data


})
function formatTimeRange(startTime, endTime) {
  const startDate = new Date(startTime);
  const endDate = new Date(endTime);

  // 格式化时间为 HH:mm
  const formatTime = (date) => {
    return new Intl.DateTimeFormat('zh-CN', {
      timeZone: "Asia/Shanghai",
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    }).format(date);
  };

  const formattedStartTime = formatTime(startDate);
  const formattedEndTime = formatTime(endDate);

  return `${formattedStartTime} - ${formattedEndTime}`;
}

function convertStatus(status){
  let value=''
  const list=[{
    label:'scheduled',
    value:'已预约',
    type:'primary'
  },
    {
      label:'completed',
      value:'已完成',
      type:'success'
    },
    {
      label:'canceled',
      value:'已取消',
      type:'error'
    },
  ]
  list.forEach(item=>{
    if (item.label==status){
      value=item.value
    }
  })
  return value
}

function convertToWeekday(num) {
  const weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五'];

  // 确保输入在 1 到 5 之间
  if (num >= 1 && num <= 5) {
    return weekdays[num - 1];
  }
}
// 示例预约数据
const appointments = ref([]);

// 取消预约相关的数据
const cancelDialogVisible = ref(false);
const selectedAppointment = ref(null);
const remark = ref('');

const showComplete=ref(false)

// 显示取消预约对话框
const showCancelDialog = (appointment) => {
  selectedAppointment.value = appointment;
  remark.value=appointment.remark
  cancelDialogVisible.value = true;
};

const flag=ref(false)
const complete=(async (row)=>{
  console.log(row)
  const res=await getAssessIdService(row.appointmentid)
  if (res.code===200){
    assessForm.value=JSON.parse(res.data.results)
  }
  //判断是否已经反馈过
  const flagRes=await isFeedService(row.appointmentid)
  if (flagRes.code===200){
    flag.value=flagRes.data
  }

  feedbackName.value=row.name
  feedbackId.value=row.counselorid
  appointmentid.value=row.appointmentid
  showComplete.value=true
})

const feedbackName=ref('')
const feedbackId=ref('')
const appointmentid=ref('')
const feedback=(()=>{
  showComplete.value=false
  router.push({
    path: '/layout/feedback',
    query: {
      name: feedbackName.value,
      id: feedbackId.value,
      appointmentid:appointmentid.value,
      flag:flag.value
    }
  });
})

</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.awsCenter {
  display: flex;
  justify-content: center;
  align-items: center;
}
.dialog-footer {
  text-align: right;
}
</style>
